package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.JobSpecialConfig;
import com.ruoyi.system.mapper.JobSpecialConfigMapper;
import com.ruoyi.system.service.AppSignLimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Service
public class AppSignLimitServiceImpl implements AppSignLimitService {

    @Autowired
    private JobSpecialConfigMapper jobSpecialConfigMapper;

    @Override
    public boolean signLimit(JobSpecialConfig jobSpecialConfig) {
        //根据作业类型 + 环节名称查询配置
        List<JobSpecialConfig> jobSpecialConfigs = jobSpecialConfigMapper.queryAll(jobSpecialConfig);
        if (CollectionUtils.isEmpty(jobSpecialConfigs)) {
            log.info("审批流程未配置 参数:{} 结果:{}", JSON.toJSONString(jobSpecialConfig), JSON.toJSONString(jobSpecialConfigs));
            return false;
        }

        JobSpecialConfig specialConfig = jobSpecialConfigs.stream().findFirst().orElse(null);
        if (null == specialConfig || StringUtils.isEmpty(specialConfig.getHandById())) {
            log.info("审批人未配置 参数:{} 结果:{}", JSON.toJSONString(jobSpecialConfig), JSON.toJSONString(specialConfig));
            return false;
        }

        //获取当前登录用户
        Long userId = SecurityUtils.getLoginUser().getUserId();
        boolean contains = specialConfig.getHandById().contains(",");
        if (contains) {
            String[] split = specialConfig.getHandById().split(",");
            for (String value : split) {
                if (Long.valueOf(value).equals(userId)) {
                    return true;
                }
            }
        } else {
            if (Long.valueOf(specialConfig.getHandById()).equals(userId)) {
                return true;
            }
        }

        return false;
    }
}
